<template>
  <div v-show="visible">
    <div class="grid_cont">
      <div style="display: flex">
        <div style="width: 3px; height: 18px; background-color: rgba(204, 53, 47, 1)"></div>
        <div style="margin-left: 10px; font-size: 16px; line-height: 16px">{{
          formParams.title
        }}</div>
      </div>
      <div
        style="width: 100%;height: 1px;background-color: rgba(245, 245, 245, 1);margin-top: 16px;margin-bottom: 30px;">
      </div>
      <el-form ref="formRef" :rules="rules" :model="formParams" style="margin-left: 14px; text-align: right"
        label-width="112px">
        <el-row>
          <el-col :span="8" style="min-width:400px;">
            <el-form-item required label="姓名：" prop="residentName">
              <el-input placeholder="请输入姓名" v-model="formParams.residentName" style="width: 280px" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="min-width:400px;">
            <el-form-item label="性别：" prop="sex">
              <el-radio-group v-model="formParams.sex">
                <el-radio label="1">男</el-radio>
                <el-radio label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" style="min-width:400px;">
            <el-form-item required label="身份证号：" prop="idNumber">
              <el-input v-model="formParams.idNumber" placeholder="请输入身份证号" style="width: 280px" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="min-width:400px;">
            <el-form-item required label="出生日期：" prop="birthDate">
              <el-date-picker v-model="formParams.birthDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" type="date"
                placeholder="请选择出生日期" style="width: 280px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" style="min-width:400px;">
            <el-form-item required label="类型：" prop="type">
              <el-select v-model="formParams.type" @change="typeChange" placeholder="请选择居民类型" placement="bottom"
                style="width: 280px">
                <el-option v-for="item in optiontype" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="min-width:400px;">
            <el-form-item required label="联系电话：" prop="phone">
              <el-input v-model="formParams.phone" placeholder="请输入联系电话" style="width: 280px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" style="min-width:400px;">
            <el-form-item required label="户籍地：" v-if="formParams.type !== '2'" prop="optionplace">
              <el-cascader style="width: 280px" filterable placeholder="可直接搜区县例如：延长县然后选中" class="profile-cascader"
                :options="pcaTextArr" v-model="formParams.optionplace" @change="placeChange" />
            </el-form-item>
          </el-col>
          <el-col :span="8" style="min-width:400px;">
            <el-form-item label="民族：" v-if="formParams.type !== '2'" prop="nation">
              <el-select v-model="formParams.nation" filterable placeholder="可直接搜民族例如：汉族然后选中" placement="bottom"
                style="width: 280px">
                <el-option v-for="item in optionnation" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" style="min-width:400px;">
            <el-form-item required label="是否户主：" v-if="formParams.type !== '2'" prop="isHolder"
              style="line-height: 40px">
              <el-radio-group v-model="formParams.isHolder" @change="isHolderChange">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="min-width:400px;">
            <el-form-item label="年收入(万)：" v-if="formParams.type !== '2'" prop="income">
              <el-input v-model="formParams.income" placeholder="请输入年收入" style="width: 280px" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8" style="min-width:400px;">
            <el-form-item required label="与户主关系：" v-if="formParams.type !== '2' && formParams.isHolder === '0'"
              prop="relationship">
              <el-select v-model="formParams.relationship" placeholder="请选择与户主关系" placement="bottom"
                style="width: 280px">
                <el-option v-for="item in optionrelation" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item required label="选择户主：" v-if="formParams.type !== '2' && formParams.isHolder === '0'"
              prop="holderId">
              <el-select v-model="formParams.holderId" filterable placeholder="可直接搜户主名然后选中" placement="bottom"
                style="width: 280px">
                <el-option v-for="item in optionholderId" :key="item.id" :label="item.residentName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item required label="选择房屋：" v-if="formParams.type !== '2'" prop="houseNumber">
              <el-select v-model="formParams.houseNumber" filterable placeholder="可直接搜房号例如：23然后选中" placement="bottom"
                style="width: 280px">
                <el-option v-for="(item, index) in optionhouseid" :key="index" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="min-width:400px;">
            <el-form-item label="照片：" v-if="formParams.type !== '2'" prop="photo">
              <UploadImg v-model="formParams.photo" :limit="1" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="display: flex; margin-bottom: 20px">
        <div style="width: 3px; height: 18px; background-color: rgba(204, 53, 47, 1)"></div>
        <div style="margin-left: 10px; font-size: 16px; line-height: 16px">居民标签</div>
      </div>
      <el-form :model="formData" style="margin-left: 14px;text-align:right;" label-width="112px">
        <el-row>
          <el-col :span="16">
            <el-form-item label="标签类型：" v-model="optionlabel">
              <div v-for="(item, index) in optionlabel" class="identity_style" :key="item.value"
                :class="{ selected: item.selected }" :title="item.label" @click="colorbtn(index)">
                {{ item.label }}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="grid_cont2">
      <el-button class="grid_btn" @click="gridCancel" style="
          background-color: rgba(255, 255, 255, 1);
          border: 1px solid rgba(187, 187, 187, 1);
          color: rgba(142, 142, 142, 1);
        ">取消</el-button>
      <el-button class="grid_btn" @click="gridSure"
        style="background-color: #ff9900; border: 1px solid #ff9900; color: #fff">确定</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { regionData, pcaTextArr } from 'element-china-area-data'
import * as getgridApi from '@/api/countryside/gridmanagement/index'
import globalApi from '@/api/spb/global'
const formRef = ref() // 搜索的表单
const formData = reactive({
  optionlabel: []
})
const rules = reactive({
  residentName: [{ required: true, message: '姓名不能为空！', trigger: 'change' }],
  idNumber: [
    { required: true, message: '身份证号不能为空！', trigger: 'change' },
    {
      pattern:
        /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
      message: '请输入正确的身份证号码',
      trigger: 'blur'
    }
  ],
  type: [{ required: true, message: '类型不能为空！', trigger: 'change' }],
  birthDate: [{ type: 'date', required: true, message: '出生日期不能为空！', trigger: 'change' }],
  optionplace: [{ required: true, message: '户籍地不能为空！', trigger: 'change' }],
  phone: [
    { required: true, message: '联系电话不能为空！', trigger: 'change' },
    {
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ],
  houseNumber: [{ required: true, message: '选择房屋不能为空！', trigger: 'change' }],
  holderId: [{ required: true, message: '选择户主不能为空！', trigger: 'change' }],
  isHolder: [{ required: true, message: '是否户主不能为空！', trigger: 'change' }],
  relationship: [{ required: true, message: '与户主关系不能为空！', trigger: 'change' }]
})
const optionlabel = ref([])
const formParams = reactive({
  residentName: '',
  idNumber: '',
  type: '',
  birthDate: '',
  optionplace: [],
  province: '',
  city: '',
  area: '',
  address: '',
  phone: '',
  houseNumber: '',
  nation: '',
  isHolder: '1',
  holderId: '',
  income: '',
  relationship: '',
  sex: '1',
  photo: '',
  title: ''
})
const visible = ref(false)
/** 获取居民类型列表 */
const optiontype = ref([])
const gettypeTypeData = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_resident_type'
  }
  globalApi.getDictData(params).then((res) => {
    optiontype.value = res.list
  })
}
/** 获取居民标签列表 */
const getresidentLabel = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_resident_label'
  }
  globalApi.getDictData(params).then((res) => {
    optionlabel.value = []
    res.list.forEach((item) => {
      optionlabel.value.push({
        label: item.label,
        value: item.value,
        selected: false
      })
    })
  })
}
const optionhouseid = ref([])
/** 获取房屋类型全列表 */
const getHouse = () => {
  getgridApi.getHouse().then((res) => {
    let data = reactive(res)
    data.forEach((item) => {
      optionhouseid.value.push(item.houseNumber)
    })
    optionhouseid.value = [...new Set(optionhouseid.value)]
  })
}
/** 选项卡颜色 */
const colorbtn = (index) => {
  optionlabel.value[index].selected = !optionlabel.value[index].selected
}
/** 获取民族类型列表 */
const optionnation = ref([])
const getnationTypeData = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_nation'
  }
  globalApi.getDictData(params).then((res) => {
    optionnation.value = res.list
  })
}
/** 获取与户主关系类型列表 */
const optionrelation = ref([])
const relationholder = ref(null)
const getholdTypeData = () => {
  optionrelation.value = []
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'countryside_relationship'
  }
  globalApi.getDictData(params).then((res) => {
    res.list.forEach((item) => {
      if (item.label !== '户主') {
        optionrelation.value.push(item)
      }
      if (item.label === '户主') {
        relationholder.value = item.value
      }
    })
  })
}
/** 获取户主列表 */
const optionholderId = ref([])
const getholderIdTypeData = () => {
  getgridApi.getHolder().then((res) => {
    optionholderId.value = res
  })
}
const props = defineProps({
  addShow: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object
  }
})

const emit = defineEmits(['getaddShow', 'geteditData'])
watch(
  () => props.addShow,
  (val) => {
    visible.value = val
  },
  { immediate: true }
)
watch(
  () => props.editData,
  (val) => {
    optionlabel.value = []
    if (val) {
      formParams.residentName = val.residentName
      formParams.idNumber = val.idNumber
      formParams.type = JSON.stringify(val.residentType)
      formParams.birthDate = String(val.birthDate)
      formParams.address = val.address
      formParams.phone = val.telephone
      formParams.houseNumber = val.houseNumber
      formParams.nation = JSON.stringify(val.nation)
      formParams.isHolder = val.isHolder
      formParams.income = val.income
      formParams.relationship = JSON.stringify(val.relationship)
      formParams.holderId = (val.holderId === 0 ? null : val.holderId)
      formParams.sex = val.sex
      formParams.photo = val.photo
      formParams.title = val.dialogtitle
      formParams.optionplace = val.place
      optionlabel.value = val.optionlabel
      if (val.dialogtitle === '新增居民') {
        getresidentLabel()
      }
      if (props.addShow == true) {
        getHouse()
        gettypeTypeData()
        getholderIdTypeData()
        getholdTypeData()
        getnationTypeData()
        formRef.value.validate()
      }
    }
  },
  { immediate: true }
)
//赋值給级联选择器
const options = ref(regionData)
const placeChange = () => {
  if (
    formParams.optionplace[0] != null &&
    formParams.optionplace[1] != null &&
    formParams.optionplace[2] != null
  ) {
    formParams.address =
      formParams.optionplace[0] + formParams.optionplace[1] + formParams.optionplace[2]
  }
}
/** 取消按钮操作 */
const gridCancel = () => {
  visible.value = false
  emit('getaddShow', visible.value)
  emit('geteditData', props.editData.pageNo)
}

/** 确定按钮操作 */
let labelList = reactive([])
const gridSure = async () => {
  await formRef.value.validate()
  labelList = []
  if (formParams.isHolder === '1') {
    formParams.relationship = relationholder.value
  }
  if (formParams.relationship === '') {
    formParams.relationship = 0
  }
  optionlabel.value.forEach((item) => {
    if (item.selected === true) {
      labelList.push(item.value)
    }
  })
  if (labelList.length === 0) {
    labelList = null
  } else {
    labelList = labelList.join(',')
  }
  const ResidentData = {
    residentName: formParams.residentName,
    residentType: formParams.type,
    address: formParams.address,
    houseNumber: formParams.houseNumber,
    isHolder: JSON.parse(formParams.isHolder),
    relationship: formParams.relationship,
    holderId: formParams.holderId,
    sex: JSON.parse(formParams.sex),
    idNumber: formParams.idNumber,
    birthDate: formParams.birthDate,
    telephone: formParams.phone,
    nation: formParams.nation,
    income: formParams.income,
    photo: formParams.photo,
    province: formParams.province,
    city: formParams.city,
    area: formParams.area,
    residentLabel: labelList
  }
  if (ResidentData.residentLabel === null) {
    ResidentData.residentLabel = ''
  }
  if (formParams.title === '新增居民') {
    ElMessageBox.confirm('是否确认新增居民?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      getgridApi.createResident(ResidentData).then((res) => {
        if (res) {
          ElMessage.success('新增成功！')
          optionlabel.value = []
          formRef.value.resetFields()
          emit('geteditData', props.editData.pageNo)
          visible.value = false
          emit('getaddShow', visible.value)
        }
      })
    }).catch(() => {
      ElMessage.info('已取消新增居民')
    })
  }
  if (formParams.title === '编辑居民') {
    ElMessageBox.confirm('是否确认编辑居民?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      ResidentData.id = props.editData.id
      ResidentData.auditStatus = props.editData.auditStatus
      getgridApi.updateResident(ResidentData).then((res) => {
        if (res) {
          ElMessage.success('修改成功！')
          optionlabel.value = []
          emit('geteditData', props.editData.pageNo)
          visible.value = false
          emit('getaddShow', visible.value)
        }
      })
    }).catch(() => {
      ElMessage.info('已取消编辑居民')
    })
  }
}

//居民类型变化
const typeChange = () => {
  if (formParams.type === '1') {
    formParams.address = '陕西省延安市延长县'
    formParams.optionplace = ['陕西省', '延安市', '延长县']
    if (formParams.title === '新增居民') {
      formParams.isHolder = '1'
      formParams.nation = ''
      formParams.holderId = null
    } else {
      formParams.address = props.editData.address
      formParams.optionplace = props.editData.place
      formParams.nation = JSON.stringify(props.editData.nation)
      formParams.houseNumber = props.editData.houseNumber
      formParams.relationship = JSON.stringify(props.editData.relationship)
      if (JSON.parse(formParams.relationship) === 0 || formParams.relationship === relationholder.value) {
        formParams.address = '陕西省延安市延长县'
        formParams.optionplace = ['陕西省', '延安市', '延长县']
        formParams.isHolder = '1'
        formParams.holderId = 0
      }
    }
  } else {
    formParams.optionplace = []
    formParams.houseNumber = ''
    formParams.isHolder = '0'
    formParams.address = ''
    formParams.nation = 1
    if (formParams.isHolder === '0') {
      formParams.relationship = ''
    } else {
      formParams.relationship = JSON.stringify(props.editData.relationship)
    }
    formParams.holderId = (props.editData.holderId === 0 ? '' : props.editData.holderId)
  }
}

const isHolderChange = () => {
  if (formParams.isHolder === '1') {
    formParams.relationship = relationholder.value
    formParams.holderId = 0
  } else {
    if (formParams.title === '新增居民') {
      formParams.relationship = ''
      formParams.holderId = ''
    } else {
      formParams.holderId = (props.editData.holderId === 0 ? '' : props.editData.holderId)
      formParams.relationship = (JSON.stringify(props.editData.relationship) == relationholder.value || formParams.relationship == 0 || JSON.stringify(props.editData.relationship) == 0 ? '' : JSON.stringify(props.editData.relationship))
    }
  }

}
onMounted(() => {
})
</script>
<style scoped>
.grid_cont {
  min-height: 600px;
  background: #fff;
}

.grid_cont2 {
  width: 100%;
  background: #fff;
  height: 65px;
  justify-content: center;
  align-items: center;
  display: flex;
  padding: 0;
  box-shadow: 0px -2px 6px 0px rgba(188, 188, 188, 0.65);
}

.grid_btn {
  width: 80px;
  height: 30px;
}

.grid_btn:hover {
  opacity: 0.8;
}

.avatar-uploader .avatar {
  width: 112px;
  height: 112px;
  display: block;
}

::v-deep .avatar-uploader .el-upload {
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

::v-deep .avatar-uploader .el-upload:hover {
  border-color: #cc352f;
}

::v-deep .el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 112px;
  height: 112px;
  text-align: center;
}

::v-deep .el-radio__input.is-checked .el-radio__inner {
  border-color: #cc352f !important;
  background-color: #cc352f !important;
}

::v-deep .el-radio__inner:hover {
  border-color: #cc352f !important;
}

::v-deep .el-radio__input.is-checked+.el-radio__label {
  color: #cc352f !important;
}

::v-deep .el-cascader .el-input.is-focus .el-input__wrapper {
  box-shadow: 0 0 0 1px #cc352f !important;
}

::v-deep .upload .el-upload .el-upload-dragger {
  border: 1px solid var(--el-border-color-darker) !important;
}

::v-deep .upload .el-upload .el-upload-dragger:hover {
  border: 1.5px solid #ccc !important;
}

.identity_style {
  min-width: 77px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border-radius: 5px;
  padding: 0 5px;
  margin: 0px 10px 10px 0px;
  font-size: 12px;
  border: none;
  cursor: pointer;
  user-select: none;
  background: #eff0f0;
  color: #888;
  border: 1px solid #eff0f0;
  font-weight: 550;
}

.selected {
  border: 1px solid rgba(16, 90, 215, 1);
  color: #437bc7;
  background: #f1f8ff;
}

.identity_style:hover {
  opacity: 0.8;
}
</style>